<?php
/**
 * User: @lose
 * Date: 2020/10/12
 * Time: 4:43 下午
 */

namespace Frieza\Modules\Topic\Controllers;

use Doraemon\model\TopTopic as mTopTopic;
use Encore\Admin\Layout\Content;
use Doraemon\service\admin\TopTopic as sTopTopic;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use App\Pockets\GridDataModel as pGridDataModel;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\TopicActivity;
use Doraemon\model\Topic\TopicActivity as mTopicActivity;

class TopTopicController
{
    public function index(Content $content, Request $request, $topId = 0)
    {
        $where = $this->buildWhere($request->all(), $topId);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $list = sTopTopic::getList($where, $limit);
        $topicId = array_column($list['list'], 'topic_id');
        $topicList = mTopicActivity::getInfoByIds($topicId);
        $gridModel = new pGridDataModel($list['list'], $list['total']);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($topicList) {
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->equal('is_over', '是否结束')->checkbox([1 => '是']);
                });
                $grid->paginate(20);
                $grid->disableExport();
                $grid->disableRowSelector();
//                $grid->disableFilter();

                $grid->column('topic_id', '话题id');
                $grid->column('topic_title', '话题名称')->display(function ()use($topicList){
                    return $topicList[$this->topic_id]['title'];
                });
                $grid->column('start_time', '开始时间');
                $grid->column('end_time', '结束时间');
                $grid->column('top_sttaus', '展示状态')->display(function () {
                    if($this->start_time < date('Y-m-d H:i:s') && $this->end_time > date('Y-m-d H:i:s')) {
                        $showStatus = '进行中';
                    } else if ($this->end_time < date('Y-m-d H:i:s')) {
                        $showStatus = '已结束';
                    } else {
                        $showStatus = '未开始';
                    }
                    return $showStatus;
                });
                $grid->column('user_profile', '分群信息')->userProfile();
                $grid->column('admin_id', '创建者')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                });
            }
        );

        return $content->header('话题置顶列表')
                    ->breadcrumb(['text' => '话题列表', 'url' => '/topic/new'], ['text' => '话题置顶列表'])
                    ->row($grid);
    }

    public function create(Content $content, $topicId = 0, $id = 0)
    {
        $where = ['status[!]' => mTopicActivity::STATUS_DELETE];
        $topicAll = mTopicActivity::select(['id', 'title'], $where);
        $topicList = [];
        foreach ($topicAll as $val) {
            $topicList[$val['id']] = $val['title'];
        }
        $info = [];
        if ($id) {
            $info = sTopTopic::getInfo($id);
        }
        $form = new Form($info);
        $form->hidden('id', 'id');
        $form->select('topic_id', '话题')->options($topicList)->required();
        $form->datetimeRange('start_time', 'end_time', '置顶时间')->attribute('autocomplete', 'off')->required();
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action("/admin/topic/{$topicId}/topTopic/save");

        return $content->header('话题置顶编辑')
            ->breadcrumb(
                ['text' => '话题列表', 'url' => '/topic/new'],
                ['text' => '话题置顶列表', 'url' => "topic/new/toplist"],
                ['text' => '话题置顶编辑']
            )->body($form);
    }

    public function save(Request $request, $topicId = 0)
    {
        try {
            $id = $request->input('id', 0);
            $topicId = $request->input('topic_id');
            $data = [
                'topic_id' => $topicId,
                'start_time' => $request->input('start_time', ''),
                'end_time' => $request->input('end_time', ''),
                'admin_id' => Admin::user()->id,
                'top_status' => mTopTopic::STATUS_NORMAL
            ];

            if ($data['start_time'] == $data['end_time']) {
                throw new \Exception('置顶时间不能相等');
            }

            $id = sTopTopic::save($id, $data, $request->input('user_profile'));
            if ($id) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect(url("/admin/topic/new/toplist"))->with(compact('success'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function delete($id)
    {
        $id = sTopTopic::delete($id, Admin::user()->id);
        if ($id) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => '删除失败',
            ]);
        }
    }

    private function buildWhere($params, $topId)
    {
        if (isset($params['start_time']) && $params['start_time']) {
            $where['start_time[>=]'] = $params['start_time'];
        }

        if (isset($params['end_time']) && $params['end_time']) {
            $where['end_time[>=]'] = $params['end_time'];
        }
        if ($topId) {
            $where['topic_id'] = $topId;
        }

        if (in_array(1, $params['is_over'] ?? [])) {
            $where["end_time[<=]"] = date('Y-m-d H:i:s', time());
        } else {
            $where["end_time[>]"] = date('Y-m-d H:i:s', time());
        }
        $where['top_status'] = mTopTopic::STATUS_NORMAL;

        return $where;
    }

    /**
     * 话题频道推荐置顶列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function topList(Request $request, Content $content)
    {
        $list = sTopTopic::getTopListAll();
        if(isset($list['list']) && is_array($list['list']) && $list['list']) {
            $topicIds = array_column($list['list'], 'topic_id');
            $topicInfos = TopicActivity::getByIds($topicIds);
            $topicArrs = [];
            if($topicInfos && is_array($topicInfos)) {
                foreach($topicInfos as $topicInfo) {
                    $topicArrs[$topicInfo['id']] = $topicInfo;
                }
            }
            foreach($list['list'] as &$topInfo) {
                $topInfo['title'] = $topicArrs[$topInfo['topic_id']]['title'];
            }
        }


        $gridModel = new pGridDataModel($list['list'], $list['total']);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disableActions();
                $grid->disableCreateButton();

                $grid->column('id', '话题置顶id')->sort();
                $grid->column('topic_id', '话题id');
                $grid->column('title', '话题标题');
                $grid->column('start_time', '开始时间');
                $grid->column('end_time', '结束时间');
                $grid->column('top_sttaus', '展示状态')->display(function () {
                    if($this->start_time < date('Y-m-d H:i:s') && $this->end_time > date('Y-m-d H:i:s')) {
                        $showStatus = '进行中';
                    } else if ($this->end_time < date('Y-m-d H:i:s')) {
                        $showStatus = '已结束';
                    } else {
                        $showStatus = '未开始';
                    }
                    return $showStatus;
                });
                $grid->column('user_profile', '分群信息')->userProfile();
                $grid->column('admin_id', '创建者')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                });
            }
        );
        return $content->header('话题置顶列表')
            ->breadcrumb(['text' => '话题列表', 'url' => '/topic/index'], ['text' => '话题置顶列表'])
            ->row($grid);
    }

    /**
     * 话题频道推荐置顶排序
     * @param Request $request
     */
    public function sortTop(Request $request)
    {
        $request = $request->all();
        $sortArr = $request['sort'];
        if($sortArr && is_array($sortArr)) {
            foreach($sortArr as $id => $sort) {
                mTopTopic::save($id, [
                    'edittime' => date('Y-m-d H:i:s', time()),
                    'top_sort' => (int) $sort
                ]);
            }
        }
    }
}